package cn.unknowpupil.init.service.system.impl;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RuntimeUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.log.StaticLog;
import cn.unknowpupil.init.common.constant.CommonConstants;
import cn.unknowpupil.init.domain.system.SysBackup;
import cn.unknowpupil.init.exceptions.HealthException;
import cn.unknowpupil.init.mapper.system.SysBackupMapper;
import cn.unknowpupil.init.properties.FileProperties;
import cn.unknowpupil.init.service.system.ISysBackupService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * Created at 2020/12/14 by w10g <br>
 * Initialize SysBackupServiceImpl ... <br>
 *
 * @author unknowpupil
 * @since 0.0.1
 */
@Service
public class SysBackupServiceImpl extends ServiceImpl<SysBackupMapper, SysBackup> implements ISysBackupService {

    @Autowired
    private FileProperties fileProperties;

    @Value("${spring.datasource.username}")
    private String username;

    @Value("${spring.datasource.password}")
    private String password;


    private QueryWrapper<SysBackup> getQueryWrapper(SysBackup backup) {
        return new QueryWrapper<SysBackup>().like(StrUtil.isNotBlank(backup.getName()), "name", backup.getName())
                .between(StrUtil.isNotBlank(backup.getBeginTime()) && StrUtil.isNotBlank(backup.getEndTime()), "create_time", backup.getBeginTime(), backup.getEndTime()).orderByDesc("create_time");
    }



    @Override
    public SysBackup info(Long id) {
        return super.getById(id);
    }

    @Override
    public boolean delete(Long[] ids) {
        List<Long> collect = Stream.of(ids).collect(Collectors.toList());
        return removeByIds(collect);
    }

    @Override
    public IPage<SysBackup> page(int current, int size, SysBackup sysBackup) {
        IPage<SysBackup> page = new Page<>(current,size);
        IPage<SysBackup> backupPage = super.page(page, getQueryWrapper(sysBackup));
        return backupPage;
    }

    @Override
    public boolean create(SysBackup backup) {
        String name = DateUtil.format(new Date(), DatePattern.PURE_DATETIME_PATTERN);
        backup.setName(name);
        String filePath = fileProperties.getPath().getResource() + "backup/";
        File uploadDir = new File(filePath);
        if (!uploadDir.exists()){
            uploadDir.mkdirs();
        }
        String cmd = "cmd /c mysqldump -u" + username + " -p" + password + " " + CommonConstants.DB_NAME + " > "
                + filePath + CommonConstants.DB_NAME + "_" + name + ".sql";
        backup.setPath(filePath + CommonConstants.DB_NAME + "_" + name + ".sql");
        //执行备份命令
        try {
            StaticLog.info("执行备份命令：" + cmd);
            RuntimeUtil.exec(cmd);
        } catch (Exception ex) {
            throw new HealthException(ex.getMessage());
        }
        return  super.save(backup);

    }

    @Override
    public boolean restore(Long id) {
        SysBackup backup = super.getById(id);
        if (backup != null) {
            String cmd = "cmd /c mysql -u" + username + " -p" + password + " " + CommonConstants.DB_NAME + " < " + backup.getPath();
            //执行还原命令
            try {
                StaticLog.info("执行还原命令：" + cmd);
                RuntimeUtil.exec(cmd);
            } catch (HealthException ex) {
                throw ex;
            }
        }
        return true;
    }
}
